<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        .box {
            margin: 20px auto;
            width: 600px;
        }


        .ta {
            width: 100%;
            text-align: center;
            border-collapse: collapse;
        }

        th {
            background-color: #959dad;
            color: #ffffff;
            border: 1px solid #ffffff;
            padding: 8px;
        }

        td {
            background-color: #ffffff;
            border-bottom: 1px solid #959dad;
            height: 40px;
        }

        .login-form {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
        }

        .login-form input {
            margin: 5px 0;
            padding: 4px;
            width: 200px;
        }

        .submit {
            margin-top: 10px;
            padding: 4px 10px;
            cursor: pointer;
        }

        .set,
        .delete {
            margin: 0 5px;
            padding: 2px 8px;
            cursor: pointer;
        }
    </style>
    <link rel="stylesheet" href="../axios/bootstrap.css">
    <script src="../axios/bootstrap.bundle.js"></script>
</head>

<body>
    <script></script>
    <div class="box">
        <h1>图书管理</h1>
        <table class="ta">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>出版社</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody class="body"></tbody>
        </table>
    </div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary add-btn" data-bs-toggle="modal" data-bs-target="#exampleModal">
        +添加
    </button>

    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">图书管理</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form class="login-form">
                    <input type="hidden" class="id">
                    书名:<input type="text" name="bookname"><br>
                    作者:<input type="text" name="author"><br>
                    出版社:<input type="text" name="publisher"><br>
                </form>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary guanji" data-bs-dismiss="modal">关鸡</button>
                    <button type="button" class="btn btn-primary zouni1">走你</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="exampleModal0" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">图书管理</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form class="login-form">
                    <input type="hidden" class="id">
                    书名:<input type="text" name="bookname" class="bookname"><br>
                    作者:<input type="text" name="author" class="author"><br>
                    出版社:<input type="text" name="publisher" class="publisher"><br>
                </form>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary guanji" data-bs-dismiss="modal">关鸡</button>
                    <button type="button" class="btn btn-primary zouni2">走你</button>
                </div>
            </div>
        </div>
    </div>


    <script src="../axios/form-serialize.js"></script>
    <script src="../axios/axios.min.js"></script>
    <script>
        //获取tbody
        const tbody = document.querySelector('.body')
        //刷新数据
        //获取数据并渲染在页面上
        const creator = '扣你鸡娃'
        function render() {
            axios({
                url: 'http://hmajax.itheima.net/api/books',
                method: 'get',
                // 3.4 替换为变量
                params: {
                    creator
                }
            }).then(res => {
                console.log(res);

                const htmlArr = res.data.data.map((item, index) => {
                    const { author, bookname, publisher, id } = item
                    // 2.2 在删除按钮上保存id
                    return `<tr>
                <td>${index + 1}</td>
                <td>${bookname}</td>
                <td>${author}</td>
                <td>${publisher}</td>
                <td data-id='${id}'>
                  <span data-id="${id}" class="del">删除</span>
                  <span data-id="${id}" class="edit">编辑</span>
                </td>
              </tr>`
                })
                const htmlStr = htmlArr.join('')
                tbody.innerHTML = htmlStr
            })

        }
        render()
        //删除图书
        document.querySelector('.body').addEventListener('click', function (e) {
            // console.log(e.target)
            if (!e.target.classList.contains('del')) {
                return
            }
            const { id } = e.target.parentNode.dataset
            console.log(id);

            axios({
                url: `http://hmajax.itheima.net/api/books/${id}`,
                method: 'delete'
            }).then(res => {
                // console.log(res)
                // 2.6 删除成功之后 重新获取数据并渲染
                render()
            })
        })
        //新增图书
        // 新增图书（绑定到“走你”按钮）
        document.querySelector('.zouni1').addEventListener('click', function (e) {
            // 获取新增模态框的表单（注意：表单在 #exampleModal 里，不是 #exampleModal0）
            const addForm = document.querySelector('#exampleModal .login-form');
            // 收集表单数据（使用 form-serialize 插件）
            const data = serialize(addForm, { hash: true, empty: true });

            // 提交到服务器（注意字段映射：后端需要 bookname、author、publisher）
            axios({
                url: 'http://hmajax.itheima.net/api/books',
                method: 'POST',
                data: {
                    ...data, // 表单的 commit 对应后端的 publisher
                    creator       // 创作者（固定值）
                }
            }).then(res => {
                // 关闭模态框（使用 Bootstrap 5 的模态框 API）
                const modalElement = document.querySelector('#exampleModal');
                const addModal = bootstrap.Modal.getInstance(modalElement); // 获取已有实例
                if (addModal) {
                    // 重置表单
                    addForm.reset();
                    addModal.hide(); // 关闭模态框
                }

                // 重新渲染表格
                render();
                console.log(res.data);
            })
        });
        //编辑图书
        //先获取然后渲染
        document.querySelector('tbody').addEventListener('click', function (e) {
            if (!e.target.classList.contains('edit')) {
                return
            }
            const { id } = e.target.parentNode.dataset
            axios({
                url: `http://hmajax.itheima.net/api/books/${id}`,
                method: 'GET'
            }).then(res => {
                console.log(res.data.data);
                const modal = document.querySelector('#exampleModal0')
                const addmodal = new bootstrap.Modal(modal)
                addmodal.show()
                for (const key in res.data.data) {
                    document.querySelector(`#exampleModal0 .${key}`).value = res.data.data[key]
                }
            })
        })
        document.querySelector('.zouni2').addEventListener('click', () => {
            const data = serialize(document.querySelector('#exampleModal0 .login-form'), { hash: true, empty: true })
            console.log(data);
            axios({
                url: `http://hmajax.itheima.net/api/books/${data.id}`,
                method: 'PUT',
                data: data
            }).then(res => {
                console.log(res)
                const editModalElement = document.querySelector('#exampleModal0');
                const editModal = bootstrap.Modal.getInstance(editModalElement);
                if (editModal) {
                    editModal.hide(); // 关闭模态框
                }
                render()
            })
        })
    </script>
</body>

</html>